package com.sf.service.impl;

import com.sf.domain.Department;
import com.sf.mapper.DepartmentMapper;
import com.sf.qo.QueryObject;
import com.sf.service.IDepartmentService;
import com.sf.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class DepartmentServiceImpl implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;


    @Override
    public PageResult query(QueryObject queryObject) {
        // 如何去判断数据库当中是否有数据
        // 1 查询数据库当中总条数, 如果为0 表述数据库中没有数据
        Integer count = departmentMapper.selectForCount();
        if(count == 0 ){
            return new PageResult(queryObject.getCurrentPage(),
                    queryObject.getPageSize(),
                    Collections.emptyList(),
                    0);
        }
        // 2 如果有数据进行分页
        List<Department> list =  departmentMapper.selectForList(queryObject);
        return new PageResult(queryObject.getCurrentPage(),queryObject.getPageSize(),list,count);
    }

    @Override
    public void saveOrUpdate(Department department) {
        // 区分他是新增还是编辑
        if(department.getId() == null){
            departmentMapper.insert(department);
        }else{
            departmentMapper.update(department);
        }
    }

    @Override
    public void delete(Long id) {
        departmentMapper.delete(id);
    }

    @Override
    public Department get(Long id) {
        return departmentMapper.get(id);
    }

    @Override
    public List<Department> listAll() {
        return departmentMapper.list();
    }
}
